import 'package:flutter/material.dart';
import 'package:flutter_demo/core/common/values/server.dart';
import 'package:flutter_demo/ui/pages/refresh/list_page_controller.dart';
import 'package:flutter_demo/ui/pages/refresh/list_page_state.dart';
import 'package:get/get.dart';
import 'package:keframe/keframe.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

/*
列表
*/
//https://www.bilibili.com/video/BV1154y1H7vL/?spm_id_from=pageDriver&vd_source=20caa5cc4d6cd22edbf2158c1c6e6320
class ListPage extends StatelessWidget {
  static const String routeName = "/refresh";
  ListPage({super.key});
  //和get 的区别不会执行生命周期函数
  //final controller = GetInstance().putOrFind(() => ListPageController());
  //Get.find 执行生命周期函数
  final controller = Get.find<ListPageController>();

  @override
  Widget build(BuildContext context) {
    //controller.gePageList(refresh: true);
    print("ListPage build----------");
    return Scaffold(
        extendBodyBehindAppBar: true,
        body: Stack(children: [
          controller.obx(
              (state) {
                //数据加载完成后监听 重新build list
                controller.refreshController.loadComplete();
                //controller.refreshController.loadComplete()
                logger.i("refreshCompleted");
                return _buildListView(context, state);
              },
              onEmpty: const Text("empty"),
              onError: (err) {
                logger.e(err.toString());
                controller.refreshController.refreshFailed();
                return Text("error");
              },
              onLoading: Text("onLoading-----"))
        ]));
  }

  Widget _buildListView(BuildContext context, ListPageState? state) {
    final listScroll = ScrollController();
    if (state != null) {
      logger.i("expirationTime");
      controller.expirationTime = DateTime.now().millisecondsSinceEpoch + 4;
    }
    //滚动条控制，大于15个时候调用刷新接口
    listScroll.addListener(() {
      controller.isScrolled.value = listScroll.position.pixels >= 15.0;
    });

    return SmartRefresher(
        controller: controller.refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: () {
          //页面刷新调用加载数据
          logger.d('上拉刷新');
          controller.gePageList(refresh: true);
          //去掉刷新按钮和，下拉完成不能重用。 只可用于上拉。
          controller.refreshController.refreshCompleted();
        },
        onLoading: () async {
          logger.d('下拉刷新-');
          await controller.loadMore();
        },
        //child: _buildListContent2(context, state, listScroll));
        child: _buildListContent3(context, state, listScroll));
  }

  //基于GridView
  Widget _buildListContent(
      BuildContext context, ListPageState? state, ScrollController listScroll) {
    return GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: 0,
          crossAxisSpacing: 1,
          childAspectRatio: 10,
        ),
        controller: listScroll,
        //padding: const EdgeInsets.all(10),
        //physics: const NeverScrollableScrollPhysics(),
        itemCount: state?.blocks.length,
        itemBuilder: (context, index) {
          final item = state?.blocks.elementAt(index);
          logger.i("列表重建----------------------$index");
          return Text(
            item?.blockCode ?? "",
          );
        });
  }

  //基于listView
  //ListView.separated可以生成列表项之间的分割器，它除了比ListView.builder多了一个separatorBuilder参数，该参数是一个分割器生成器
  Widget _buildListContent2(
      BuildContext context, ListPageState? state, ScrollController listScroll) {
    Widget redDivider = const Divider(color: Colors.red);
    Widget blueDivider = const Divider(color: Colors.blue);
    return ListView.separated(
        padding: const EdgeInsets.only(bottom: 1),
        controller: listScroll,
        itemBuilder: (context, index) {
          logger.i("列表重建----------------------$index");
          return FrameSeparateWidget(
              index: index,
              placeHolder: Container(
                color: Get.theme.cardColor,
                height: 10,
              ),
              child: SizedBox(
                  width: 10,
                  child: ListTile(
                    title: Text("我是列表$index"),
                  )));
        },
        separatorBuilder: (BuildContext context, int index) {
          return index % 2 == 0 ? redDivider : blueDivider;
        },
        itemCount: state != null ? state.blocks.length : 0);
  }

  //基于Sliver
  Widget _buildListContent3(
      BuildContext context, ListPageState? state, ScrollController listScroll) {
    return CustomScrollView(slivers: [
      SliverPersistentHeader(
        delegate: _MyDelegate("abc"),
        pinned: true,
      ),
      SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
          Blocks? block = state?.blocks.elementAt(index);
          logger.i("列表重建----------------------$index");
          return ListTile(
            title: Text(block!.blockCode),
            subtitle: Text(block.blockCode),
          );
        }, childCount: state?.blocks.length),
      )
    ], controller: listScroll);
  }
}

/*
 *自定义吸顶效果 
 */
class _MyDelegate extends SliverPersistentHeaderDelegate {
  final title;

//构造方法传进来
  _MyDelegate(this.title);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
        color: Colors.blue,
        //填充整个空间
        child: FittedBox(
          child: Text(title),
        ));
  }

  //占用空间大小
  @override
  double get maxExtent => 50;

  @override
  double get minExtent => 50;

  @override
  bool shouldRebuild(covariant _MyDelegate oldDelegate) {
    return oldDelegate.title != title;
  }
}
